package com.sdy.dcsb.web.controller;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.sdy.common.model.Response;
import com.sdy.dcsb.biz.model.*;
import com.sdy.dcsb.biz.service.*;
import com.sdy.dcsb.web.controller.inboundservice.util.LocalhostUtil;
import com.sdy.dcsb.web.util.SearchBrowserKeywordsUtil;
import com.sdy.fs.api.FsApi;
import com.sdy.mvc.controller.BaseController;
import com.sdy.resdir.api.ResApi;
import com.sdy.resdir.api.param.ResParamInfoParam;
import com.sdy.resdir.api.param.UpdateApiResInfoParam;
import com.sdy.usercenter.api.UserQueryApi;
import com.sdy.usercenter.api.dto.DeptDto;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.*;
import java.util.*;
import static org.springframework.util.StringUtils.isEmpty;

/**
 * @author lx
 */

@Slf4j
@RestController
@RequestMapping("/APIEdit")
@Api(tags = "API编辑相关接口")
public class EsbServiceApiController extends BaseController {
    @Autowired
    private EsbServiceApiService esbServiceApiService;
    @Autowired
    private EsbServiceApiLogService esbServiceApiLogService;
    @Autowired
    private EsbInboundMainService esbInboundMainService;
    @Autowired
    private EsbServiceApiParamService esbServiceApiParamService;
    @Autowired
    private EsbServiceApiFileService esbServiceApiFileService;
    @Autowired
    private ResApi resApi;
    @Autowired
    private EsbInboundHttpService esbInboundHttpService;
    @Autowired
    private EsbInboundWebserviceService esbInboundWebserviceService;
    @Autowired
    private EsbInboundH5Service esbInboundH5Service;
    @Autowired
    private UserQueryApi userQueryApi;
    @Autowired
    private SUserService sUserService;
    @Autowired
    private EsbAppService esbAppService;

    @GetMapping("/selectAtomService")
    @ApiOperation("API编辑展示页面，分页，可按编码或名称模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "current", value = "当前页"),
            @ApiImplicitParam(dataType = "Integer", name = "size", value = "每页数量"),
            @ApiImplicitParam(dataType = "Integer", name = "type", value = "查询类别,1:服务名称 2:服务编码 其他:查全部"),
            @ApiImplicitParam(dataType = "String", name = "message", value = "查询值"),
    })
    public Response selectAtomService(Integer type, String message, Page<EsbServiceApi> page) {
        LambdaQueryWrapper<EsbServiceApi> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(EsbServiceApi::getId);
        if(isEmpty(type)) {
            return Response.error("查询类别不能为空");
        }
        if(!isEmpty(message)) {
            try {
                message = URLDecoder.decode(message,"utf-8");
            }catch(IOException e) {

            }
            if(type.equals(1)) {
                wrapper.like(EsbServiceApi::getServname,message);
            }else if(type.equals(2)) {
                wrapper.like(EsbServiceApi::getServcode,message);
            }
        }
        IPage<EsbServiceApi> result = esbServiceApiService.page(page, wrapper);
        return Response.success(result);

    }

    @GetMapping("/download")
    @ApiOperation("API编辑下载接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前id"),
    })
    public Response download(Integer id, HttpServletRequest request, HttpServletResponse response){
        if (!isEmpty(id)){
            String username = sUserService.getUser(request);
            boolean save = saveApiOperationLog(id, username, "13", "API接口文档下载");

            if (save){
            }else {
                return Response.error("记录下载操作日志失败");
            }
            try {
                EsbServiceApi api = esbServiceApiService.getById(id);

                Configuration configuration = new Configuration();
                configuration.setDefaultEncoding("UTF-8");
                configuration.setServletContextForTemplateLoading(request.getServletContext(), "/webapp/public/template/layout");
                Template template = configuration.getTemplate("test.ftl", "UTF-8");
                String servname = api.getServname();
                File outfile = new File(request.getServletContext().getRealPath("/") + servname + ".doc");
                Integer apiId = api.getId();

                /**
                 * 存放的是api的信息
                 */
                Map<String, Object> apiMap = new HashMap<>();
                apiMap.put("servname",api.getServname());
                apiMap.put("apiaddress",api.getApiaddress()+ "/" +api.getServcode() + "@" +api.getServversion());
                if (isEmpty(api.getDescription())){
                    apiMap.put("description", " ");
                }else {
                    apiMap.put("description", api.getDescription());
                }
                String reqExample = api.getReqExample();
                if (isEmpty(reqExample)){
                    apiMap.put("reqExample"," ");
                }else {
                    JSONObject jsonObj = new JSONObject();
                    try {
                        jsonObj = JSONObject.parseObject(reqExample);
                        apiMap.put("reqExample",jsonObj.toJSONString());
                    } catch (JSONException e) {
                        apiMap.put("reqExample",reqExample);
                    }
                }
                String respExample = api.getRespExample();
                if (isEmpty(respExample)){
                    apiMap.put("respExample"," ");
                }else {
                    JSONObject jsonObj = new JSONObject();
                    try {
                        jsonObj = JSONObject.parseObject(respExample);
                        apiMap.put("respExample",jsonObj.toJSONString());
                    } catch (JSONException e) {
                        apiMap.put("respExample",respExample);
                    }
                }

                /**
                 * 存参数信息
                 */
                List<Map<String,Object>> paramsList = new ArrayList<>();

                /**
                 * 入参信息集合
                 */
                Map<String, Object> inParamsList = new HashMap<>();

                /**
                 * 入参信息集合
                 */
                QueryWrapper<EsbServiceApiParam> inPar = new QueryWrapper<>();
                inPar.eq("api_id",apiId);
                inPar.eq("parammode",0);
                List<EsbServiceApiParam> inParams = esbServiceApiParamService.list(inPar);

                /**
                 * 入参信息填充数据
                 */
                List<Map<String,Object>> inParamsLi = new ArrayList<>();
                for (int i = 0; i < inParams.size(); i++) {
                    Map<String, Object> inPaMap = new HashMap<>();
                    inPaMap.put("paramname",inParams.get(i).getParamname());
                    inPaMap.put("paramtype",inParams.get(i).getParamtype());
                    inPaMap.put("paramremarker",inParams.get(i).getParamremarker());
                    if (inParams.get(i).getIsNecessary().equals("0")){
                        inPaMap.put("isNecessary","是");
                    }else {
                        inPaMap.put("isNecessary","否");
                    }
                    inParamsLi.add(inPaMap);
                }
                inParamsList.put("inParams",inParamsLi);
                paramsList.add(inParamsList);


                /**
                 * 出参信息集合
                 */
                Map<String, Object> outParamsList = new HashMap<>();

                /**
                 * 出参信息集合
                 */
                QueryWrapper<EsbServiceApiParam> outPar = new QueryWrapper<>();
                outPar.eq("api_id",apiId);
                outPar.eq("parammode",1);
                List<EsbServiceApiParam> outParams = esbServiceApiParamService.list(outPar);

                /**
                 * 出参信息填充数据
                 */
                List<Map<String,Object>> outParamsLi = new ArrayList<>();
                for (int a = 0; a < outParams.size(); a++) {
                    Map<String, Object> outPaMap = new HashMap<>();
                    outPaMap.put("paramname",outParams.get(a).getParamname());
                    outPaMap.put("paramtype",outParams.get(a).getParamtype());
                    outPaMap.put("paramremarker",outParams.get(a).getParamremarker());
                    outParamsLi.add(outPaMap);
                }
                outParamsList.put("outParams",outParamsLi);
                paramsList.add(outParamsList);

                /**
                 * 将参数信息放入api中
                 */
                apiMap.put("allList",paramsList);

                Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8"),10240);
                template.process(apiMap,out);
                out.flush();
                out.close();

                /**
                 * 读
                 */
                OutputStream ops = response.getOutputStream();
                InputStream ins=new FileInputStream(outfile);
                byte[] buffer = new byte[8192];
                int bytesRead = 0 ;
                response.setContentType("text/html;charset=utf-8");
                boolean isMSIE = SearchBrowserKeywordsUtil.isMSBrowser(request);
                if (isMSIE) {
                    /**
                     * IE、360兼容版浏览器的乱码问题解决
                     */
                    servname = URLEncoder.encode(servname , "UTF-8");
                } else {
                    /**
                     *万能乱码问题解决
                     */
                    servname = new String(servname.getBytes("UTF-8"), "ISO-8859-1");
                }
                response.setHeader("Content-Disposition", "attachment; filename="+ servname+".doc");

                /*response.setHeader("Content-Disposition", "attachment; filename="+
                        new String((servname+".doc").getBytes("UTF-8"), "ISO-8859-1"));*/
                while((bytesRead = ins.read(buffer, 0, 8192)) != -1){
                    ops.write(buffer, 0, bytesRead);
                }
                ops.close();
                ins.close();
            } catch (Exception e) {
                log.info(e.getMessage());
            }
            return Response.success();
        }else {
            return Response.error("请求id不能为空");
        }
    }

    @GetMapping("/selectDetail")
    @ApiOperation("详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前服务id"),
            @ApiImplicitParam(dataType = "String", name = "servcode", value = "服务编码"),
    })
    public Response selectDetail(Integer id,String servcode) {
        if (!isEmpty(id)){
            return Response.success(esbServiceApiService.getById(id));
        }
        if (!isEmpty(servcode)){
            QueryWrapper<EsbServiceApi> wrapper = new QueryWrapper<>();
            wrapper.eq("servcode",servcode);
            return Response.success(esbServiceApiService.getOne(wrapper));
        }
        return Response.error("请传入指定参数id或编码");
    }

    @GetMapping("/updateOneMess")
    @ApiOperation("修改单条服务信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前服务id"),
            @ApiImplicitParam(dataType = "String", name = "description", value = "服务说明"),
            @ApiImplicitParam(dataType = "String", name = "name", value = "联系人姓名"),
            @ApiImplicitParam(dataType = "String", name = "phone", value = "联系方式"),
            @ApiImplicitParam(dataType = "String", name = "apiaddress", value = "服务访问地址"),
            @ApiImplicitParam(dataType = "String", name = "providedept", value = "数源部门"),
            @ApiImplicitParam(dataType = "String", name = "providedeptCode", value = "数源部门编码"),
            @ApiImplicitParam(dataType = "String", name = "shareType", value = "共享类型"),
            @ApiImplicitParam(dataType = "String", name = "reqExample", value = "请求示例"),
            @ApiImplicitParam(dataType = "String", name = "respExample", value = "返回示例"),
            @ApiImplicitParam(dataType = "Integer", name = "dataUpdateCycle", value = "数据更新周期 实时1、每小时2、每天3、每月4、 每季度5、每半年6、每年7、 不更新8，不定时9"),
            @ApiImplicitParam(dataType = "Integer", name = "dataPlatformId", value = "共享平台资源id"),
    })
    public Response update(HttpServletRequest request, Integer id, String description, String name, String phone, String apiaddress,
                           String providedept, String providedeptCode, String shareType, String reqExample, String respExample,
                           Integer dataUpdateCycle, Integer dataPlatformId) {
        try {
            if (!isEmpty(description)){
                description = URLDecoder.decode(description, "utf-8");
            }
            if (!isEmpty(name)){
                name = URLDecoder.decode(name, "utf-8");
            }
            if (!isEmpty(phone)){
                phone = URLDecoder.decode(phone, "utf-8");
            }
            if (!isEmpty(providedept) || !isEmpty(providedeptCode)){
                providedept = URLDecoder.decode(providedept, "utf-8");
                providedeptCode = URLDecoder.decode(providedeptCode, "utf-8");
            }
            apiaddress = URLDecoder.decode(apiaddress, "utf-8");

            shareType = URLDecoder.decode(shareType, "utf-8");
            if (!isEmpty(reqExample)){
                reqExample = URLDecoder.decode(reqExample, "utf-8");
            }
            if (!isEmpty(respExample)){
                respExample = URLDecoder.decode(respExample, "utf-8");
            }

        } catch (IOException e) {
            return Response.error("请按要求输入参数");
        }
        if (!isEmpty(id)) {
            EsbServiceApi esbServiceApi = new EsbServiceApi();
            esbServiceApi.setDescription(description);
            esbServiceApi.setName(name);
            esbServiceApi.setPhone(phone);
            esbServiceApi.setApiaddress(apiaddress);
            esbServiceApi.setProvidedept(providedept);
            esbServiceApi.setProvidedeptCode(providedeptCode);
            esbServiceApi.setShareType(shareType);
            esbServiceApi.setReqExample(reqExample);
            esbServiceApi.setRespExample(respExample);
            esbServiceApi.setStatus("0");
            esbServiceApi.setDataUpdateCycle(dataUpdateCycle);
            esbServiceApi.setDataPlatformId(dataPlatformId);
            EsbServiceApi apiServiceById = esbServiceApiService.getById(id);

            if (apiServiceById.getApiaddress().equals(apiaddress) && apiServiceById.getShareType().equals(shareType) && Objects.equals(apiServiceById.getProvidedept(), providedept) &&
                    Objects.equals(apiServiceById.getProvidedeptCode(), providedeptCode)  && apiServiceById.getDataUpdateCycle().equals(dataUpdateCycle) && Objects.equals(apiServiceById.getDescription(),description) && Objects.equals(apiServiceById.getRespExample(),respExample) &&
                    Objects.equals(apiServiceById.getReqExample(),reqExample) && Objects.equals(apiServiceById.getName(),name) && Objects.equals(apiServiceById.getPhone(),phone) && Objects.equals(apiServiceById.getDataPlatformId(),dataPlatformId)
                    ){
                return Response.error("信息未修改");
            }else {
                boolean updateMess = esbServiceApiService.update(esbServiceApi, new UpdateWrapper<EsbServiceApi>().eq("id", id));
                if (updateMess){
                    String username = sUserService.getUser(request);
                    boolean apiLogSave = saveApiOperationLog(id, username, "1", "修改API信息");
                    if (apiLogSave){
                        return Response.success("API修改成功");
                    }else {
                        return Response.error("操作日志记录失败");
                    }
                }else {
                    return Response.error("修改失败");
                }
            }
        }
        return Response.error("请求id不能为空");
    }

    @GetMapping("/operateApi")
    @ApiOperation("API编辑操作提交审核接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "esbServiceApi id"),
    })
    public Response operateApi(HttpServletRequest request, Integer id) {
        if (!isEmpty(id)){
            EsbServiceApi esbServiceApi = new EsbServiceApi();
            esbServiceApi.setStatus("1");
            boolean upda = esbServiceApiService.update(esbServiceApi,new UpdateWrapper<EsbServiceApi>().eq("id",id));
            if (upda) {
                String username = sUserService.getUser(request);
                boolean apiLogSave = saveApiOperationLog(id, username, "2", "API提交审核");
                if (apiLogSave) {
                    return Response.success("API提交审核成功");
                } else {
                    return Response.error("操作日志记录失败");
                }
            }else {
                return Response.error("API提交审核失败");
            }
        }else {
            return Response.error("id不能为空");
        }
    }

    @GetMapping("/operateApiPass")
    @ApiOperation("API编辑操作审核通过接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "esbServiceApi id"),
    })
    public Response operateApiPass(HttpServletRequest request, Integer id) {
        if (!isEmpty(id)){
            EsbServiceApi esbServiceApi = new EsbServiceApi();
            esbServiceApi.setStatus("2");
            boolean upda = esbServiceApiService.update(esbServiceApi,new UpdateWrapper<EsbServiceApi>().eq("id",id));
            if (upda) {
                String username = sUserService.getUser(request);
                boolean apiLogSave = saveApiOperationLog(id, username, "3", "API审核通过");
                if (apiLogSave) {
                    return Response.success("API审核通过成功");
                } else {
                    return Response.error("操作日志记录失败");
                }
            }else {
                return Response.error("API审核通过失败");
            }
        }else {
            return Response.error("id不能为空");
        }
    }

    @GetMapping("/operateApiGoBack")
    @ApiOperation("API编辑操作回退接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "esbServiceApi id"),
    })
    public Response operateApiGoBack(HttpServletRequest request, Integer id) {
        if (!isEmpty(id)){
            EsbServiceApi esbServiceApi = new EsbServiceApi();
            esbServiceApi.setStatus("0");
            boolean upda = esbServiceApiService.update(esbServiceApi,new UpdateWrapper<EsbServiceApi>().eq("id",id));
            if (upda) {
                String username = sUserService.getUser(request);
                boolean apiLogSave = saveApiOperationLog(id, username, "4", "API回退");
                if (apiLogSave) {
                    return Response.success("API回退成功");
                } else {
                    return Response.error("操作日志记录失败");
                }
            }else {
                return Response.error("API回退失败");
            }
        }else {
            return Response.error("id不能为空");
        }
    }


    @GetMapping("/operateApiCancle")
    @ApiOperation("API编辑操作作废接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "esbServiceApi id"),
    })
    public Response operateApiCancle(HttpServletRequest request, Integer id) {
        if (!isEmpty(id)){
            EsbServiceApi esbServiceApi = new EsbServiceApi();
            esbServiceApi.setStatus("4");
            boolean upda = esbServiceApiService.update(esbServiceApi,new UpdateWrapper<EsbServiceApi>().eq("id",id));
            if (upda) {
                String username = sUserService.getUser(request);
                boolean apiLogSave = saveApiOperationLog(id, username, "6", "API作废");
                if (apiLogSave) {
                    return Response.success("API作废成功");
                } else {
                    return Response.error("操作日志记录失败");
                }
            }else {
                return Response.error("API作废失败");
            }
        }else {
            return Response.error("id不能为空");
        }
    }


    @GetMapping("/operateApiStartUsing")
    @ApiOperation("API编辑操作启用接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "esbServiceApi id"),
    })
    public Response operateApiStartUsing(HttpServletRequest request, Integer id) {
        if (!isEmpty(id)){
            EsbServiceApi esbServiceApi = new EsbServiceApi();
            esbServiceApi.setStatus("0");
            boolean upda = esbServiceApiService.update(esbServiceApi,new UpdateWrapper<EsbServiceApi>().eq("id",id));
            if (upda) {
                String username = sUserService.getUser(request);
                boolean apiLogSave = saveApiOperationLog(id, username, "7", "API启用");
                if (apiLogSave) {
                    return Response.success("API启用成功");
                } else {
                    return Response.error("操作日志记录失败");
                }
            }else {
                return Response.error("API启用失败");
            }
        }else {
            return Response.error("id不能为空");
        }
    }

    @PostMapping("/saveApi")
    @ApiOperation("新建接口")
    @Transactional
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "servname", value = "服务名称"),
            @ApiImplicitParam(dataType = "String", name = "servcode", value = "服务编码"),
            @ApiImplicitParam(dataType = "String", name = "servversion", value = "服务版本"),
            @ApiImplicitParam(dataType = "String", name = "description", value = "服务说明"),
            @ApiImplicitParam(dataType = "String", name = "name", value = "联系人姓名"),
            @ApiImplicitParam(dataType = "String", name = "phone", value = "联系方式"),
            @ApiImplicitParam(dataType = "String", name = "apiaddress", value = "服务访问地址"),
            @ApiImplicitParam(dataType = "String", name = "providedept", value = "数源部门"),
            @ApiImplicitParam(dataType = "String", name = "providedeptCode", value = "数源部门编码"),
            @ApiImplicitParam(dataType = "String", name = "shareType", value = "共享类型"),
            @ApiImplicitParam(dataType = "String", name = "reqExample", value = "请求示例"),
            @ApiImplicitParam(dataType = "String", name = "respExample", value = "返回示例"),
            @ApiImplicitParam(dataType = "String", name = "dataUpdateCycle", value = "数据更新周期 实时1、每小时2、每天3、每月4、每季度5、每半年6、每年7、不更新8，不定时9"),
            @ApiImplicitParam(dataType = "String", name = "dataPlatformId", value = "共享平台资源id"),
    })
    public Response saveApi(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String apiaddress =(String) map.get("apiaddress");
        String servname =(String) map.get("servname");
        String servcode =(String) map.get("servcode");
        String servversion =(String) map.get("servversion");
        String description =(String) map.get("description");
        String phone =(String) map.get("phone");
        String name =(String) map.get("name");
        String reqExample =(String) map.get("reqExample");
        String respExample =(String) map.get("respExample");
        Integer dataPlatformId = null;
        if(!isEmpty(map.get("dataPlatformId"))) {
            dataPlatformId= (Integer)map.get("dataPlatformId");
        }
        String providedept =(String) map.get("providedept");
        String providedeptCode =(String) map.get("providedeptCode");
        String shareType =(String) map.get("shareType");
        Integer dataUpdateCycle =(Integer) map.get("dataUpdateCycle");
        if (!isEmpty(servname) && !isEmpty(servversion) && !isEmpty(shareType)
                && !isEmpty(dataUpdateCycle) && !isEmpty(providedept)
                && !isEmpty(providedeptCode) && !isEmpty(servcode)){
            QueryWrapper<EsbServiceApi> wrapper = new QueryWrapper<>();
            wrapper.eq("servcode",servcode);
            wrapper.eq("servversion",servversion);
            EsbServiceApi apiMess = esbServiceApiService.getOne(wrapper);
            if(isEmpty(apiMess)) {
                if(isEmpty(apiaddress)) {
                    QueryWrapper<EsbInboundMain> esbInboundMainWrapper = new QueryWrapper<>();
                    esbInboundMainWrapper.eq("servcode", servcode);
                    esbInboundMainWrapper.eq("servversion", servversion);
                    List<EsbInboundMain> esbInboundMainWrapperResult = esbInboundMainService.list(esbInboundMainWrapper);
                    if(esbInboundMainWrapperResult.size() == 0) {
                        return Response.error("选择的服务不存在，请检查");
                    }
                    Integer serviceId = esbInboundMainWrapperResult.get(0).getServiceid();
                    EsbInboundHttp esbInboundHttpResult = esbInboundHttpService.getById(serviceId);
                    EsbInboundWebservice esbInboundWebserviceResult = esbInboundWebserviceService.getById(serviceId);
                    EsbInboundH5 esbInboundH5Result = esbInboundH5Service.getById(serviceId);
                    String ip = LocalhostUtil.getIpAddress();
                    String port = "";
                    QueryWrapper<EsbApp> esbAppWrapper = new QueryWrapper();
                    esbAppWrapper.eq("ip", ip);
                    esbAppWrapper.eq("apptype", "3");
                    List<EsbApp> esbAppResult = esbAppService.list(esbAppWrapper);
                    if(esbAppResult.size() == 0) {
                        return Response.error("获取服务器ip失败，错误ip为：" + ip);
                    }
                    port = esbAppResult.get(0).getHttpport();
                    if(!isEmpty(esbInboundHttpResult)){
                        apiaddress = "http://" + ip + ":" + port + "/DCSBWeb/servlets";
                    }else if(!isEmpty(esbInboundWebserviceResult)) {
                        apiaddress = "http://" + ip + ":" + port + "/DCSBWeb/services";
                    }else if(!isEmpty(esbInboundH5Result)) {
                        apiaddress = "http://" + ip + ":" + port + "/DCSBWeb/h5servlets";
                    }else {
                        apiaddress = "http://" + ip + ":" + port + "/DCSBWeb/servlets";
                    }
                }
                EsbServiceApi esbServiceApi = new EsbServiceApi();
                esbServiceApi.setServname(servname);
                esbServiceApi.setServcode(servcode);
                esbServiceApi.setServversion(servversion);
                esbServiceApi.setDescription(description);
                esbServiceApi.setName(name);
                esbServiceApi.setPhone(phone);
                esbServiceApi.setApiaddress(apiaddress);
                esbServiceApi.setProvidedept(providedept);
                esbServiceApi.setProvidedeptCode(providedeptCode);
                esbServiceApi.setShareType(shareType);
                esbServiceApi.setReqExample(reqExample);
                esbServiceApi.setRespExample(respExample);
                esbServiceApi.setStatus("0");
                esbServiceApi.setDataUpdateCycle(dataUpdateCycle);
                esbServiceApi.setDataPlatformId(dataPlatformId);
                boolean saveApi = esbServiceApiService.save(esbServiceApi);
                if (saveApi) {
                    String username = sUserService.getUser(request);
                    boolean apiLogSave = saveApiOperationLog(esbServiceApi.getId(), username, "0", "API新建");
                    if (apiLogSave) {
                        return Response.success(esbServiceApi.getId());
                    } else {
                        return Response.error("操作日志记录失败");
                    }
                }else {
                    return Response.error("API新建失败");
                }
            }else {
                return Response.error("新建的服务已存在，请检查");
            }
        }else {
            return Response.error("新增信息不能为空，请输入有效信息");
        }
    }

    @GetMapping("/editHistoryApi")
    @ApiOperation("API编辑历史查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "apiId", value = "当前apiId"),
    })
    public Response editHistoryApi(Integer apiId, Page<EsbServiceApiLog> page) {
        if (!isEmpty(apiId)){
            QueryWrapper<EsbServiceApiLog> wrapper = new QueryWrapper<>();
            wrapper.eq("api_id",apiId);
            wrapper.orderByDesc("OPERATION_TIME");
            return Response.success(esbServiceApiLogService.page(page,wrapper));
        }else {
            return Response.error("apiId不能为空");
        }
    }

    @GetMapping("/inOutParameterApi")
    @ApiOperation("API输入输出参数,新增接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "apiId", value = "API id对应ESB_SERVICE_API.ID,新增需传"),
            @ApiImplicitParam(dataType = "String", name = "paramname", value = "参数名称"),
            @ApiImplicitParam(dataType = "String", name = "paramremarker", value = "参数说明"),
            @ApiImplicitParam(dataType = "String", name = "paramtype", value = "参数值类型"),
            @ApiImplicitParam(dataType = "String", name = "parammode", value = "参数类型。0:入参,1:出参"),
    })
    public Response inOutParameterApi(HttpServletRequest request, Integer apiId,String paramname, String paramremarker, String paramtype,
                                      String isNecessary ,String parammode) {
        if (!isEmpty(apiId) && !isEmpty(parammode) && !isEmpty(paramname) && !isEmpty(paramtype)){
            EsbServiceApiParam esbServiceApiParam = new EsbServiceApiParam();
            try {
                paramname = URLDecoder.decode(paramname, "utf-8");
                paramtype = URLDecoder.decode(paramtype, "utf-8");
                if (!isEmpty(paramremarker)) {
                    paramremarker = URLDecoder.decode(paramremarker, "utf-8");
                }
            } catch (IOException e) {

            }
            String username = sUserService.getUser(request);
            esbServiceApiParam.setParammode(parammode);
            esbServiceApiParam.setParamremarker(paramremarker);
            esbServiceApiParam.setParamtype(paramtype);
            esbServiceApiParam.setParamname(paramname);
            esbServiceApiParam.setApiId(apiId);
            if ("0".equals(parammode) && !isEmpty(isNecessary)) {
                esbServiceApiParam.setIsNecessary(isNecessary);
                boolean saveOne = esbServiceApiParamService.save(esbServiceApiParam);
                if (saveOne){
                    boolean apiLogSave = saveApiOperationLog(apiId, username, "10", "API单条入参新增");
                    if (apiLogSave) {
                        return Response.success("单条输入参数新增成功");
                    } else {
                        return Response.error("单条输入参数新增日志记录失败");
                    }
                }else {
                    return Response.error("单条输入参数新增失败");
                }
            }
            esbServiceApiParam.setIsNecessary("0");
            boolean save = esbServiceApiParamService.save(esbServiceApiParam);
            if (save){
                boolean apiLogSave = saveApiOperationLog(apiId, username, "11", "API单条出参新增");
                if (apiLogSave) {
                    return Response.success("单条输出参数新增成功");
                } else {
                    return Response.error("单条输出参数新增日志记录失败");
                }
            }else {
                return Response.error("单条输出参数新增失败");
            }
        }else {
            return Response.error("请先保存API基本信息,参数信息不能为空");
        }
    }


    @GetMapping("/outParameterApi")
    @ApiOperation("API输出输入输出参数,修改接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "id 修改需传"),
            @ApiImplicitParam(dataType = "String", name = "paramname", value = "参数名称"),
            @ApiImplicitParam(dataType = "String", name = "paramremarker", value = "参数说明"),
            @ApiImplicitParam(dataType = "String", name = "paramtype", value = "参数值类型"),
            @ApiImplicitParam(dataType = "String", name = "parammode", value = "参数类型。0:入参,1:出参"),
    })
    public Response outParameterApi(HttpServletRequest request, Integer id, String paramname, String paramremarker,
                                    String paramtype, String isNecessary ,String parammode) {
        if (!isEmpty(id)){
            EsbServiceApiParam esbServiceApiParam = new EsbServiceApiParam();
            try {
                if (!isEmpty(paramname) && !isEmpty(paramremarker)) {
                    paramname = URLDecoder.decode(paramname, "utf-8");
                    paramremarker = URLDecoder.decode(paramremarker, "utf-8");
                }
            } catch (IOException e) {
                log.info(e.getMessage());
            }
            esbServiceApiParam.setParamremarker(paramremarker);
            esbServiceApiParam.setParamtype(paramtype);
            esbServiceApiParam.setParamname(paramname);
            esbServiceApiParam.setParammode(parammode);
            if ("1".equals(parammode) && isEmpty(isNecessary) && !isEmpty(id)) {
                boolean update = esbServiceApiParamService.update(esbServiceApiParam,new UpdateWrapper<EsbServiceApiParam>().eq("id",id));
                if (update){
                    QueryWrapper<EsbServiceApiParam> esbServiceApiParamQueryWrapper = new QueryWrapper<>();
                    esbServiceApiParamQueryWrapper.eq("id",id);
                    EsbServiceApiParam oneParam = esbServiceApiParamService.getOne(esbServiceApiParamQueryWrapper);
                    String username = sUserService.getUser(request);
                    boolean apiLogSave = saveApiOperationLog(oneParam.getApiId(), username, "1", "API单条出参信息修改");
                    if (apiLogSave) {
                        return Response.success("出参信息修改成功");
                    } else {
                        return Response.error("单条输出参数信息修改日志记录失败");
                    }
                }else {
                    return Response.error("出参信息修改失败");
                }
            }
            esbServiceApiParam.setIsNecessary(isNecessary);
            boolean upd = esbServiceApiParamService.update(esbServiceApiParam,new UpdateWrapper<EsbServiceApiParam>().eq("id",id));
            if (upd){
                QueryWrapper<EsbServiceApiParam> esbServiceApiParamQueryWrapper = new QueryWrapper<>();
                esbServiceApiParamQueryWrapper.eq("id",id);
                EsbServiceApiParam oneParam = esbServiceApiParamService.getOne(esbServiceApiParamQueryWrapper);
                String username = sUserService.getUser(request);
                boolean apiLogSave = saveApiOperationLog(oneParam.getApiId(), username, "1", "API单条入参信息修改");
                if (apiLogSave) {
                    return Response.success("入参信息修改成功");
                } else {
                    return Response.error("单条入参数信息修改日志记录失败");
                }
            }else {
                return Response.error("入参信息修改失败");
            }
        }else {
            return Response.error("请求id不能为空");
        }
    }


    @GetMapping("/selectInOutParameterApi")
    @ApiOperation("API输入输出参数查询展示接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "parammode", value = "参数类型。0:入参,1:出参"),
            @ApiImplicitParam(dataType = "Integer", name = "apiId", value = "当前apiId"),
    })
    public Response selectInOutParameterApi(Integer apiId, String parammode, Page<EsbServiceApiParam> page) {
        if(!isEmpty(apiId) && !isEmpty(parammode)) {
            if ("0".equals(parammode)){
                QueryWrapper<EsbServiceApiParam> wrapper = new QueryWrapper<>();
                wrapper.eq("parammode",0);
                wrapper.eq("api_id",apiId);
                return Response.success(esbServiceApiParamService.page(page,wrapper));
            }else {
                QueryWrapper<EsbServiceApiParam> wrapper = new QueryWrapper<>();
                wrapper.eq("parammode",1);
                wrapper.eq("api_id",apiId);
                return Response.success(esbServiceApiParamService.page(page,wrapper));
            }
        }else {
            return Response.error("请按要求输入参数");
        }
    }

    @GetMapping("/selectInOutParameterApiOneMess")
    @ApiOperation("API输入输出参数单条信息查询")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前id"),
    })
    public Response selectInOutParameterApiOneMess(Integer id) {
        if (!isEmpty(id)){
            return Response.success(esbServiceApiParamService.getById(id));
        }else {
            return Response.error("id不能为空");
        }
    }

    @GetMapping("/deleteInOutParameterApi")
    @ApiOperation("API输入输出参数删除接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前id"),
    })
    public Response deleteInOutParameterApi(Integer id) {
        if (!isEmpty(id)){
            return Response.success(esbServiceApiParamService.removeById(id));
        }else {
            return Response.error("id不能为空");
        }
    }

    @PostMapping("/fileUp")
    @ApiOperation(value = "API输入输出参数文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "apiId", value = "apiId"),
            @ApiImplicitParam(dataType = "String", name = "parammode", value = "参数类型。0:入参,1:出参"),
    })
    public Response up(HttpServletRequest request, @RequestPart("file") MultipartFile file,
                       @RequestParam("apiId")Integer apiId, @RequestParam("parammode")String parammode){

        try{
            if(!file.getOriginalFilename().contains(".xls")) {
                return Response.error("上传文件的类型错误");
            }
            // 获取文件输入流
            InputStream inputStream = file.getInputStream();
            // 获取excel工作簿对象
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
            List<EsbServiceApiParam> esbServiceApiParamResult = excelToList(workbook, apiId, parammode);
            // 关闭输入流
            inputStream.close();
            QueryWrapper<EsbServiceApiParam> wrapper = new QueryWrapper<>();
            wrapper.eq("api_id", apiId);
            wrapper.eq("parammode", parammode);
            List<EsbServiceApiParam> apiList = esbServiceApiParamService.list(wrapper);
            if(apiList.size() > 0 ) {
                for(int i=0; i<apiList.size(); i++) {
                    esbServiceApiParamService.removeById(apiList.get(i).getId());
                }
            }
            for(int i=0; i<esbServiceApiParamResult.size(); i++) {
                EsbServiceApiParam esbServiceApiParam = new EsbServiceApiParam();
                esbServiceApiParam.setApiId(esbServiceApiParamResult.get(i).getApiId());
                esbServiceApiParam.setParammode(esbServiceApiParamResult.get(i).getParammode());
                esbServiceApiParam.setParamname(esbServiceApiParamResult.get(i).getParamname());
                esbServiceApiParam.setParamremarker(esbServiceApiParamResult.get(i).getParamremarker());
                esbServiceApiParam.setParamtype(esbServiceApiParamResult.get(i).getParamtype());
                esbServiceApiParam.setIsNecessary(esbServiceApiParamResult.get(i).getIsNecessary());
                esbServiceApiParamService.save(esbServiceApiParam);
            }
            String username = sUserService.getUser(request);
            boolean apiLogSave = true;
            if("0".equals(parammode)) {
                apiLogSave = saveApiOperationLog(apiId, username, "8", "API入参导入");
            }else {
                apiLogSave = saveApiOperationLog(apiId, username, "9", "API出参导入");
            }
            if (apiLogSave) {
                return Response.success("导入成功");
            } else {
                return Response.error("操作日志记录失败");
            }
        }catch (Exception e) {
            //return Response.error(e.getMessage());
            return Response.error("上传文件失败，请用模板文件xls上传参数，确保参数都有填写，没有空白");
        }
    }

    private List<EsbServiceApiParam> excelToList(XSSFWorkbook workbook, Integer apiId, String parammode) {
        // 得到excel工作表对象
        XSSFSheet sheetAt = workbook.getSheetAt(0);
        List<EsbServiceApiParam> list = Lists.newArrayList();
        for (Row row : sheetAt) {
            //首行（即表头）不读取
            if (row.getRowNum() == 0) {
                continue;
            }
            //读取当前行中单元格数据，索引从0开始
            String paramname = row.getCell(0).getStringCellValue();
            String paramtype = row.getCell(1).getStringCellValue();
            String paramremarker = row.getCell(2).getStringCellValue();
            String isNecessary = row.getCell(3).getStringCellValue();
            if("是".equals(isNecessary)) {
                isNecessary = "0";
            }else {
                isNecessary = "1";
            }
            EsbServiceApiParam esbServiceApiParam = new EsbServiceApiParam();
            esbServiceApiParam.setApiId(apiId);
            esbServiceApiParam.setParammode(parammode);
            esbServiceApiParam.setParamname(paramname);
            esbServiceApiParam.setParamremarker(paramremarker);
            esbServiceApiParam.setParamtype(paramtype);
            esbServiceApiParam.setIsNecessary(isNecessary);
            list.add(esbServiceApiParam);
        }
        return list;
    }

    @PostMapping("/fileAnnexUp")
    @ApiOperation("API附件信息上传")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "filePath", value = "当前文件路径"),
            @ApiImplicitParam(dataType = "Integer", name = "apiId", value = "apiId"),
            @ApiImplicitParam(dataType = "String", name = "name", value = "文件名"),
    })
    public Response fileAnnexUp(HttpServletRequest request, @RequestBody Map<String,Object> map){
        String filePath = "";
        String fileName = "";
        Integer apiId = null;
        try{
            filePath = (String)map.get("filePath");
        }catch (Exception e) {
            return  Response.error("请求数据的filePath值的字段类型不对,请用字符串类型");
        }
        try{
            fileName = (String)map.get("name");
        }catch (Exception e) {
            return  Response.error("请求数据的fileName值的字段类型不对,请用字符串类型");
        }
        apiId = (Integer) map.get("apiId");
        if (!isEmpty(filePath) && !isEmpty(apiId)){
            EsbServiceApiFile esbServiceApiFile = new EsbServiceApiFile();
            esbServiceApiFile.setApiId(apiId);
            esbServiceApiFile.setFilePath(filePath);
            esbServiceApiFile.setFilename(fileName);
            boolean save = esbServiceApiFileService.save(esbServiceApiFile);
            if (save){
                String username = sUserService.getUser(request);
                boolean apiLogSave = saveApiOperationLog(apiId, username, "12", "API附件信息上传");
                if (apiLogSave){
                    return Response.success("上传文件日志记录成功");
                }else {
                    return Response.error("上传文件日志记录失败");
                }
            }else {
                return Response.error("上传文件失败");
            }
        }
        return Response.error("请填写api基本信息");
    }

    @GetMapping("/fileExport")
    @ApiOperation("API输入输出导入导出模板下载")
    @ApiImplicitParams({
    })
    public Response fileExport(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try{
            String fileName = "API输入输出参数模板下载";
            Resource res = new ClassPathResource("/webapp/public/template/layout/API模板.xls");
            InputStream ins = res.getInputStream();
            OutputStream ops = response.getOutputStream();
            byte[] buffer = new byte[8192];
            int bytesRead = 0 ;
            response.setContentType("text/html;charset=utf-8");
            boolean isMSIE = SearchBrowserKeywordsUtil.isMSBrowser(request);
            if (isMSIE) {
                /**
                 * IE、360兼容版浏览器的乱码问题解决
                 */
                fileName = URLEncoder.encode(fileName , "UTF-8");
            } else {
                /**
                 *万能乱码问题解决
                 */
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }
            response.setHeader("Content-Disposition", "attachment; filename="+ fileName+".xls");
           /* response.setHeader("Content-Disposition", "attachment; filename="+
                    new String((fileName+".xls").getBytes("UTF-8"), "ISO-8859-1"));*/
            while((bytesRead = ins.read(buffer, 0, 8192)) != -1){
                ops.write(buffer, 0, bytesRead);
            }
            ops.close();
            ins.close();
        } catch (Exception e) {
            return Response.error("下载失败:"+e.getMessage());
        }
        return Response.success("生成成功");
    }

    @GetMapping("/accessoryEditApi")
    @ApiOperation("API编辑附件信息查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "apiId", value = "apiId"),
    })
    public Response accessoryEditApi(Integer apiId, Page<EsbServiceApiFile> page) {
        if(isEmpty(apiId)) {
            return Response.error("请求apiId不能为空");
        }
        QueryWrapper<EsbServiceApiFile> wrapper = new QueryWrapper<>();
        wrapper.eq("api_id",apiId);
        return Response.success(esbServiceApiFileService.page(page,wrapper));
    }

    @GetMapping("/accessoryDeleteApi")
    @ApiOperation("API编辑附件信息删除接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "当前id"),
    })
    public Response accessoryDeleteApi(Integer id) {
        if(isEmpty(id)) {
            return Response.error("请求id不能为空");
        }else {
            return Response.success(esbServiceApiFileService.removeById(id));
        }
    }

    @GetMapping("/accessoryDownLoadApi")
    @ApiOperation("API编辑附件信息下载接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "id"),
            @ApiImplicitParam(dataType = "Integer", name = "apiId", value = "apiId"),
    })
    public Response accessoryDownLoadApi(Integer id, Integer apiId, HttpServletRequest request, HttpServletResponse response) {
        if(!isEmpty(id) && !isEmpty(apiId)) {
            EsbServiceApiFile esbServiceApiFileResult = esbServiceApiFileService.getById(id);
            String filePath = esbServiceApiFileResult.getFilePath();
            File file = null;
            String username = sUserService.getUser(request);
            boolean apiLogSave = saveApiOperationLog(apiId, username, "13", "API附件下载");
            if (apiLogSave) {

            } else {
                return Response.error("新增操作日志失败");
            }

            try{
                URL url = new URL(filePath);
                /**
                 *  连接类的父类，抽象类
                 */
                URLConnection urlConnection = url.openConnection();

                HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
                /**
                 * 设置超时
                 */
                httpURLConnection.setConnectTimeout(1000*5);
                /**
                 * 设置请求方式，默认是GET
                 */
                /*httpURLConnection.setRequestMethod("POST");*/

                httpURLConnection.setRequestProperty("Charset", "UTF-8");
                /**
                 * 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）
                 */
                httpURLConnection.connect();
                /**
                 * 文件大小
                 */
                int fileLength = httpURLConnection.getContentLength();

           /* 控制台打印文件大小
            System.out.println("您要下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");*/

                /**
                 * 建立链接从请求中获取数据
                 */
                URLConnection con = url.openConnection();
                BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
                /**
                 * 指定文件名称(有需求可以自定义)
                 */
                QueryWrapper<EsbServiceApiFile> wrapper = new QueryWrapper<>();
                wrapper.eq("file_path",filePath);
                EsbServiceApiFile serviceApiFile = esbServiceApiFileService.getOne(wrapper);

                String fileFullName = serviceApiFile.getFilename();

                /**
                 * 指定文件存放在临时目录
                 */
                String path = request.getServletContext().getRealPath("/")+ fileFullName;

                file = new File(path);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }

                OutputStream out = new FileOutputStream(file);
                int size = 0;
                int len = 0;
                byte[] buf = new byte[2048];
                while ((size = bin.read(buf)) != -1) {
                    len += size;
                    out.write(buf, 0, size);
                    /*System.out.println("下载了-------> " + len * 100 / fileLength + "%\n");*/
                }
                bin.close();
                out.close();

                OutputStream ops = response.getOutputStream();
                InputStream ins=new FileInputStream(file);

                byte[] buffer = new byte[8192];
                int bytesRead = 0 ;
                response.setContentType("text/html;charset=utf-8");
                boolean isMSIE = SearchBrowserKeywordsUtil.isMSBrowser(request);
                if (isMSIE) {
                    /**
                     * IE、360兼容版浏览器的乱码问题解决
                     */
                    fileFullName = URLEncoder.encode(fileFullName , "UTF-8");
                } else {
                    /**
                     *万能乱码问题解决
                     */
                    fileFullName = new String(fileFullName.getBytes("UTF-8"), "ISO-8859-1");
                }
                response.setHeader("Content-Disposition", "attachment; filename="+ fileFullName);

               /* response.setHeader("Content-Disposition", "attachment; filename="+
                        new String(fileFullName.getBytes("UTF-8"), "ISO-8859-1"));*/
                while((bytesRead = ins.read(buffer, 0, 8192)) != -1){
                    ops.write(buffer, 0, bytesRead);
                }
                ops.close();
                ins.close();
            } catch (IOException e) {
                log.info(e.getMessage());
            }
            return Response.success(file);
        }else {
            return Response.error("请求id不能为空");
        }
    }


    @GetMapping("/queryPageMess")
    @ApiOperation("API审核接口,查询服务的所有分页数据，可按名称或编码模糊查询，状态查询")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "current", value = "当前页"),
            @ApiImplicitParam(dataType = "Integer", name = "size", value = "每页数量"),
            @ApiImplicitParam(dataType = "Integer", name = "type", value = "查询类别,1:服务名称 2:服务编码 其他:查全部"),
            @ApiImplicitParam(dataType = "String", name = "status", value = "状态 1:待批准,2:待发布,3:已发布 5:全部"),
            @ApiImplicitParam(dataType = "String", name = "message", value = "查询值"),
    })
    public Response queryPageMess(Integer type, String message, String status, Page<EsbServiceApi> page) {
        LambdaQueryWrapper<EsbServiceApi> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(EsbServiceApi::getId);
        if(!isEmpty(message)) {
            try {
                message = URLDecoder.decode(message,"utf-8");
            }catch(IOException e) {

            }
            if(isEmpty(type)) {
                return Response.error("查询类别不能为空");
            }
            if(type.equals(1)) {
                wrapper.like(EsbServiceApi::getServname,message);
                if ("5".equals(status)){
                    wrapper.in(EsbServiceApi::getStatus,"1","2","3");
                }else {
                    wrapper.in(EsbServiceApi::getStatus,status);
                }
            }else if(type.equals(2)) {
                wrapper.like(EsbServiceApi::getServcode,message);
                if ("5".equals(status)){
                    wrapper.in(EsbServiceApi::getStatus,"1","2","3");
                }else {
                    wrapper.in(EsbServiceApi::getStatus,status);
                }
            }
        }else {
            if ("5".equals(status)){
                wrapper.in(EsbServiceApi::getStatus,"1","2","3");
            }else {
                wrapper.in(EsbServiceApi::getStatus,status);
            }
        }
        IPage<EsbServiceApi> result = esbServiceApiService.page(page, wrapper);
        return Response.success(result);
    }

    /**
     * API审核操作中的发布接口
     * @param id, 资源id
     * @return
     */
    @GetMapping("/editApiOne")
    @ApiOperation("API审核操作中的发布接口")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "资源id"),
    })
    public Response editApiOne(HttpServletRequest request, Integer id) {
        if(!isEmpty(id)) {
            EsbServiceApi esbServiceApi = new EsbServiceApi();
            esbServiceApi.setStatus("3");
            boolean result = esbServiceApiService.update(esbServiceApi, new UpdateWrapper<EsbServiceApi>().eq("id",id));
            if(result) {
                String username = sUserService.getUser(request);
                boolean logOk = saveApiOperationLog(id, username, "5", "API发布");
                if(logOk) {
                    EsbServiceApi esbServiceApiResult = esbServiceApiService.getById(id);
                    QueryWrapper<EsbInboundMain> esbInboundMainWrapper = new QueryWrapper<>();
                    esbInboundMainWrapper.eq("servcode",esbServiceApiResult.getServcode());
                    EsbInboundMain esbInboundMainResult = esbInboundMainService.getOne(esbInboundMainWrapper);
                    if(isEmpty(esbInboundMainResult)){
                        esbServiceApi.setStatus("2");
                        esbServiceApiService.update(esbServiceApi, new UpdateWrapper<EsbServiceApi>().eq("id",id));
                        return Response.error("发布的接口服务查询不存在");
                    }
                    Integer requestType = null;
                    EsbInboundHttp esbInboundHttpResult = esbInboundHttpService.getById(esbInboundMainResult.getServiceid());
                    EsbInboundWebservice esbInboundWebserviceResult = esbInboundWebserviceService.getById(esbInboundMainResult.getServiceid());
                    EsbInboundH5 esbInboundH5Result = esbInboundH5Service.getById(esbInboundMainResult.getServiceid());
                    if(!isEmpty(esbInboundHttpResult)) {
                        requestType = esbInboundHttpResult.getHttptype();
                    }else if(!isEmpty(esbInboundWebserviceResult)) {
                        requestType = 3;
                    }else if(!isEmpty(esbInboundH5Result)) {
                        requestType = 4;
                    }else {
                        esbServiceApi.setStatus("2");
                        esbServiceApiService.update(esbServiceApi, new UpdateWrapper<EsbServiceApi>().eq("id",id));
                        return Response.error("发布的接口服务没有配置请求方式，请配置之后重新发布");
                    }
                    UpdateApiResInfoParam updateApiResInfoParam = new UpdateApiResInfoParam();
                    if(!isEmpty(esbServiceApiResult.getDataPlatformId())) {
                        if(0 != esbServiceApiResult.getDataPlatformId()) {
                            updateApiResInfoParam.setId(esbServiceApiResult.getDataPlatformId());
                        }
                    }
                    updateApiResInfoParam.setResDcsbId(id);
                    updateApiResInfoParam.setResName(esbServiceApiResult.getServname());
                    updateApiResInfoParam.setOwnApp("DCSB");
                    //updateApiResInfoParam.setInterfaceState(2);
                    updateApiResInfoParam.setIsFail(1);
                    updateApiResInfoParam.setUpdateFrequency(esbServiceApiResult.getDataUpdateCycle());
                    DeptDto deptDtoResult = userQueryApi.getDeptByCode(esbServiceApiResult.getProvidedeptCode());
                    if(isEmpty(deptDtoResult)){
                        esbServiceApi.setStatus("2");
                        esbServiceApiService.update(esbServiceApi, new UpdateWrapper<EsbServiceApi>().eq("id",id));
                        return Response.error("发布的接口服务的数源部门编码错误");
                    }
                    updateApiResInfoParam.setResSourceDeptId(deptDtoResult.getId());
                    updateApiResInfoParam.setResSourceDept(deptDtoResult.getName());
                    updateApiResInfoParam.setReturnDemo(esbServiceApiResult.getRespExample());
                    updateApiResInfoParam.setRequestDemo(esbServiceApiResult.getReqExample());
                    updateApiResInfoParam.setInterfaceName(esbServiceApiResult.getServname());
                    updateApiResInfoParam.setRequestType(requestType);
                    //updateApiResInfoParam.setSupportFormat("无用?");
                    updateApiResInfoParam.setApiDesc(esbServiceApiResult.getDescription());
                    updateApiResInfoParam.setApiAddress(esbServiceApiResult.getApiaddress()+ "/"
                            +esbServiceApiResult.getServcode()+"@"+esbServiceApiResult.getServversion());

                    QueryWrapper<EsbServiceApiParam> esbServiceApiParamQueryWrapper = new QueryWrapper<>();
                    esbServiceApiParamQueryWrapper.eq("api_id",id);
                    List<EsbServiceApiParam> list = esbServiceApiParamService.list(esbServiceApiParamQueryWrapper);
                    List<ResParamInfoParam> rpip = new ArrayList<>();
                    for(int i = 0; i<list.size(); i++) {
                        ResParamInfoParam resParamInfoParam = new ResParamInfoParam();
                        resParamInfoParam.setParameterName(list.get(i).getParamname());
                        resParamInfoParam.setType(list.get(i).getParamtype());
                        resParamInfoParam.setNecessary(Integer.valueOf(list.get(i).getIsNecessary()));
                        resParamInfoParam.setExplains(list.get(i).getParamremarker());
                        //resParamInfoParam.setInstanceValue("无");
                        resParamInfoParam.setPrimaryKey(2);
                        resParamInfoParam.setParameterType(Integer.valueOf(list.get(i).getParammode()));
                        rpip.add(resParamInfoParam);
                    }
                    updateApiResInfoParam.setParam(rpip);
                    Integer dataPlatResult = null;
                    String dataPlatResultMessage = "共享平台更新失败";
                    try{
                        dataPlatResult = resApi.saveOrUpdateApiRes(updateApiResInfoParam);
                    }catch (Exception e) {
                        esbServiceApi.setStatus("2");
                        esbServiceApiService.update(esbServiceApi, new UpdateWrapper<EsbServiceApi>().eq("id",id));
                        return Response.error("调用共享平台API出错");
                    }
                    if(dataPlatResult.equals(1)) {
                        dataPlatResultMessage = "发布成功";
                    }
                    if(isEmpty(esbServiceApiResult.getDataPlatformId())) {
                        return Response.success(dataPlatResultMessage);
                    }else {
                        if(esbServiceApiResult.getDataPlatformId().equals(0)) {
                            return Response.success(dataPlatResultMessage);
                        }else {
                            UpdateWrapper<EsbServiceApi> wrapper = new UpdateWrapper<>();
                            wrapper.eq("id", id);
                            wrapper.set("data_platform_id", 0);
                            try{
                                esbServiceApiService.update(wrapper);
                                return Response.success(dataPlatResultMessage);
                            }catch (Exception e) {
                                return Response.error(e.getMessage());
                            }
                        }
                    }

                }else {
                    esbServiceApi.setStatus("2");
                    esbServiceApiService.update(esbServiceApi, new UpdateWrapper<EsbServiceApi>().eq("id",id));
                    return Response.error("记录操作日志失败");
                }
            }else {
                return Response.error("发布失败");
            }
        }else {
            return Response.error("请求id不能为空");
        }
    }

    /**
     * 保存API操作日志的方法
     * @param apiId
     * @param username
     * @param operationType
     * @param operationMessage
     * @return
     */
    private boolean saveApiOperationLog(Integer apiId, String username, String operationType, String operationMessage) {
        EsbServiceApiLog esbServiceApiLog = new EsbServiceApiLog();
        esbServiceApiLog.setApiId(apiId);
        esbServiceApiLog.setUsername(username);
        esbServiceApiLog.setOperationTime(new Date());
        esbServiceApiLog.setOperationType(operationType);
        esbServiceApiLog.setOperationMessage(operationMessage);
        return esbServiceApiLogService.save(esbServiceApiLog);
    }

    /**
     * 获取数源部门树信息
     * @param id
     * @return
     */
    @GetMapping("/getDeptName")
    @ApiOperation("获取数源部门树信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "父id，初始值为0"),
    })
    public Response getDeptName(Integer id) {
        if(isEmpty(id)){
            return Response.error("请求id不能为空");
        }
        List<DeptDto> deptDtoResult = userQueryApi.listDept(id);
        return Response.success(deptDtoResult);
    }

    /**
     * 部门数据
     * @param message
     * @return
     */
    @GetMapping("/getDept")
    @ApiOperation("部门数据")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "message", value = "搜索部门数据"),
    })
    public Response getDept(String message) {
        if(!isEmpty(message)) {
            try{
                message = URLDecoder.decode(message,"utf-8");
                List<DeptDto> deptDtoResult = userQueryApi.listDept(message);
                return Response.success(deptDtoResult);
            }catch (Exception e) {
                return Response.error("解码失败");
            }
        }else {
            return Response.error("搜索数据不能为空");
        }
    }

}